package com.cykj.user.controller;

import com.cykj.common.core.web.domain.AjaxResult;
import com.cykj.user.dto.ShopRecommendDTO;
import com.cykj.user.python.PythonExecutor;
import com.cykj.user.mapper.ShopRecommendMapper;
import com.cykj.user.utils.RecommendProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

/**
 * 商家推荐接口控制器
 */
@RestController
@RequestMapping("/recommend")
@RequiredArgsConstructor
public class RecommendController {

    private final PythonExecutor pythonExecutor;
    private final ShopRecommendMapper shopRecommendMapper;
    private final RecommendProperties recommendProperties;

    /**
     * 核心接口：获取用户个性化推荐（商家+商品）
     * @param userId 用户ID
     */
    @GetMapping("/shop/{userId}")
    public AjaxResult getFullRecommendations(@PathVariable Long userId) {
        // 调用Python脚本获取推荐id（重试+兜底）
        List<Long> recommendBusinessIds = getRecommendIdsWithFallback(userId);
        // 查信息
        List<ShopRecommendDTO> shopList = shopRecommendMapper.selectRecommendShopsWithProducts(recommendBusinessIds);
        return AjaxResult.success("个性化推荐获取成功", shopList);
    }

    /**
     * 兜底接口：获取热门商家（推荐接口失败时调用）
     */
    @GetMapping("/shop/hot")
    public AjaxResult getHotShops() {
        // 用配置的默认商家ID
        List<ShopRecommendDTO> hotShops = shopRecommendMapper.selectRecommendShopsWithProducts(
                recommendProperties.getDefaultShopIds()
        );
        return AjaxResult.success("热门商家获取成功", hotShops);
    }

    /**
     * 私有方法：调用Python脚本+重试+兜底逻辑
     */
    private List<Long> getRecommendIdsWithFallback(Long userId) {
        int retryCount = 0;
        // 重试
        while (retryCount < recommendProperties.getMaxRetries()) {
            try {
                String jsonResult = pythonExecutor.execute(
                        recommendProperties.getScriptPath(),
                        userId.toString()
                );

                return pythonExecutor.parseJsonArray(jsonResult);
            } catch (IOException e) {
                retryCount++;
                System.err.println("Python脚本执行失败（第" + retryCount + "次重试）：" + e.getMessage());
                // 最后一次重试失败，触发兜底
                if (retryCount >= recommendProperties.getMaxRetries() && recommendProperties.isFallbackEnabled()) {
                    System.err.println("启用兜底方案，返回默认商家ID");
                    return recommendProperties.getDefaultShopIds();
                }
            }
        }
        // 重试耗尽且未启用兜底，返回空列表
        return List.of();
    }
}